<?php

define("TOKEN", "sijibaowebapp");
require "jssdk.php";

$wechatObj = new wechatCallbackapiTest();
if(isset($_GET["echostr"])){
	$wechatObj->valid();
}else{
	$wechatObj->responseMsg();
}



class wechatCallbackapiTest
{
  	private $domainname;
	private $JSSDK;
	//构造函数
	public function __construct() {
		  $this->domainname = "http://qiaodev.natapp4.cc";
    	$this->JSSDK = new JSSDK();
	}

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            switch ($RX_TYPE)
            {
                case "text":
                    $resultStr = $this->receiveText($postObj);
                    break;
                case "image":
                    //$resultStr = $this->receiveImage($postObj);
                    break;
                case "location":
                    //$resultStr = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    //$resultStr = $this->receiveVoice($postObj);
                    break;
                case "video":
                    //$resultStr = $this->receiveVideo($postObj);
                    break;
                case "link":
                    //$resultStr = $this->receiveLink($postObj);
                    break;
                case "event":
                    //$resultStr = $this->receiveEvent($postObj);
                    break;
                default:
                    //$resultStr = "unknow msg type: ".$RX_TYPE;
                    break;
            }
			if($resultStr != "nomsg")
            	echo $resultStr;
        }else {
            echo "";
            exit;
        }
    }

    private function receiveText($object)
    {
        $funcFlag = 0;
		    $userdata = json_decode($this->getUserInfo($object->FromUserName),TRUE);
        $contentStr='http://qiaodev.natapp4.cc/wx_test/test.html';
        //$contentStr = "你(".$userdata["nickname"].")发送的是文本，内容为：".$object->Content;
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }

    private function receiveImage($object)
    {
        $funcFlag = 0;
        $contentStr = "你发送的是图片，地址为：".$object->PicUrl;
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }

    private function receiveLocation($object)
    {
        $funcFlag = 0;
        $contentStr = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }

    private function receiveVoice($object)
    {
        $funcFlag = 0;
        $contentStr = "你发送的是语音，媒体ID为：".$object->MediaId;
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }

    private function receiveVideo($object)
    {
        $funcFlag = 0;
        $contentStr = "你发送的是视频，媒体ID为：".$object->MediaId;
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }

    private function receiveLink($object)
    {
        $funcFlag = 0;
        $contentStr = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $resultStr = $this->transmitText($object, $contentStr, $funcFlag);
        return $resultStr;
    }

    private function receiveEvent($object)
    {
        $contentStr = "";
        switch ($object->Event)
        {
            case "subscribe":
				$userdata = json_decode($this->getUserInfo($object->FromUserName),TRUE);
                $contentStr = "亲爱的：".$userdata["nickname"]."，欢迎关注司机宝物流";

				//关注时 如果有场景$object->EventKey为场景值  没有场景则为空
				if (isset($object->EventKey)){
	                $contentStr = "nomsg";
					if($object->EventKey != ""){
						$this->wxlog($object->EventKey,__FILE__,__LINE__);
						$scankey = str_replace("qrscene_", "", $object->EventKey);
						$contentStr = $this->getstock($scankey,$object->FromUserName);//拉取今日货源
					}
	            }
				$uploadurl = $this->domainname."/SJBWEB/Wxproject/System/uploadWchatInfo?";
				$uploadurl .= "city=".$userdata["city"];
				$uploadurl .= "&headimage=".$userdata["headimgurl"];
				$uploadurl .= "&nick=".urlencode($userdata["nickname"]);
				$uploadurl .= "&openid=".$userdata["openid"];
				$uploadurl .= "&province=".$userdata["province"];
				$uploadurl .= "&unionid=".$userdata["unionid"];
				$back = $this->http_request($uploadurl);
				$this->wxlog($back,__FILE__,__LINE__);
                break;
            case "SCAN":
				//扫描 $object->EventKey为场景值
				$this->wxlog($object->EventKey,__FILE__,__LINE__);
				$contentStr = $this->getstock($object->EventKey,$object->FromUserName);//拉取今日货源
	            break;
			case "unsubscribe":
                $contentStr = "";
                break;
			case "LOCATION":
				$contentStr = "nomsg";
//				$locurl = $this->domainname."/SJBWEB/Wxproject/WXpage/devicelogCreate?";
//				$locurl .= "openid=".$object->FromUserName;
//				$locurl .= "&latitude=".$object->Latitude;
//				$locurl .= "&longitude=".$object->Longitude;
//				//$this->wxlog($locurl,__FILE__,__LINE__);
//				$loc = $this->http_request($locurl);
            	break;
            case "CLICK":
                switch ($object->EventKey)
                {
                    default:
                        $contentStr = "你点击了: ".$object->EventKey;
                        break;
                }
                break;
            default:
                $contentStr = "receive a new event: ".$object->Event;
                break;
        }
		if(is_array($contentStr)){
            if (isset($contentStr[0]['PicUrl'])){
                $result = $this->transmitNews($object, $contentStr);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $contentStr);
            }
        }else{
        	if($contentStr!="nomsg"){
				$result = $this->transmitText($object, $contentStr);
			}else{
				$result = $contentStr;
			}
        }
        return $result;



    }

    private function transmitText($object, $content, $flag = 0)
    {
        $textTpl = "<xml>
       	<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		<FuncFlag>%d</FuncFlag>
		</xml>";
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $flag);
        return $resultStr;
    }
    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "<item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
	    </item>";
        $item_str = "";
        foreach ($newsArray as $item){
        	$item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[news]]></MsgType>
		<ArticleCount>%s</ArticleCount>
		<Articles>
		$item_str</Articles>
		</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }


	/**
     * 获取用户基本信息
     * @param $access_token 已获取的ACCESS_TOKEN
     * @param $openid 已获取的用户ID
     */

    private function getUserInfo($openid)
    {
		$access_token = $this->JSSDK->getAccessToken();
    	$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";

		$ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_HEADER,0);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 500);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//服务端校验
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//不执行严格校验
        $res = curl_exec($ch);
        curl_close($ch);
       	return $res;
    }


	/**
     * 发送http请求 支持get和post
     * @param string $url
     * @param string $data
     */
    private function http_request($url,$data = null)
    {
    	$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    	if (!empty($data)) {
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    	$output = curl_exec($curl);
		curl_close($curl);
        return $output;
    }

	private function getstock($channelcode,$openid){

		$rtn = json_decode($this->http_request($this->domainname."/SJBWEB/Wxproject/WXpage/getStockList?channelcode=".$channelcode),TRUE);

		if($rtn["error"] == 0){
			$list = $rtn["obj"]["list"];
			if($rtn["obj"]["count"] == 0){
				$contentStr = "今日没有货源";
			}
			if($rtn["obj"]["count"] > 0){
				//图文回复
				$contentStr = array();
				$num = 0;
				foreach($list as $key => $value){
					if($num == 8) break;
					if($num == 0){
						//第一条大图显示
						$contentStr[] = array(
							"Title"=>$value["channel"]["channelname"],
							"Description"=>"诚信为本诚信为本",
              "PicUrl" =>$this->domainname."/SJBWEB/Public/img/toptplmsg.jpg",
              "Url" =>""
						);
					}
					$msgtitle = "";
					$msgtitle .= $value["pristock"]["stockname"]."\n";
					$msgtitle .= $value["pristock"]["stockkindmemo"]." ".$value["pristock"]["unit"]." ".$value["pristock"]["strPrice"]."\n";
					$msgtitle .= $value["pristock"]["createdate"]."\n";
					$msgtitle .= $value["pristock"]["stockdesc"]?"备注：".$value["pristock"]["stockdesc"]:"";
					$contentStr[] = array(
						"Title"=>$msgtitle,
						"Description"=>"",
                   		"PicUrl" =>$this->domainname."/SJBWEB/Public/img/stocknum".($num+1).".png",
                   		"Url" =>$this->domainname."/SJBWEB/Wxproject/WXdriver/receiveorder?channelstockcode=".$value["channelstockcode"]
					);
					$num++;
				}
			}
		}else{
			$contentStr = "nomsg";
			$this->wxlog("货源数据拉取异常",__FILE__,__LINE__);
		}
		return $contentStr;
	}


	//打印日志
	private function wxlog($arr,$file,$line){
		if(is_array($arr)){
			$log = $arr;
		}else{
			$log["value"] = $arr;
		}
		$content = "File => ".end(explode('\\',$file))." on line:".$line."\r\n";
		$content .= date("Y/m/d H:i:s")." array(";

		foreach ($log as $key => $value) {
			if(is_array($value)){
				$content .= "\r\n    '".$key."' => '".urldecode(json_encode($value))."'";
			}else{
				$content .= "\r\n    '".$key."' => '".$value."'";
			}
		}
		$content .= "\r\n)\r\n\r\n";
        $log_filename = "log/".date("Ymd").".log";
        if(file_exists($log_filename)){
			file_put_contents($log_filename, $content ,FILE_APPEND);
        }else{
        	file_put_contents($log_filename, $content);
        }
	}
}
?>
